# model

# responsible for the parallel file-upload (RAID-1 redundancy).

from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers

from boto.connection import HTTPRequest
from boto.s3.resumable_download_handler import *
from boto.s3.connection import *
from boto.s3.key import *

from Utilities import *

from controller.BuildStorageInfo import *

from model.octopus.datastore.OctopusCloudDatabaseOpenStack import OctopusCloudDatabaseOpenStack

from google.appengine.ext.db import GqlQuery
from google.appengine.ext.blobstore import BlobInfo

from google.appengine.ext.blobstore.blobstore import BlobReader
from google.appengine.ext.blobstore.blobstore import *

import types
 
class FileUploadHandlerRaidOne(blobstore_handlers.BlobstoreUploadHandler): 
    def get(self, pSelf, uploadedFiles, key, acl):
        utilities = Utilities()
        
        username = utilities.getUsername()
        userText = utilities.getUserText()
        
        if username:
            urlText = utilities.getUrlTextLogout()
            url = utilities.getLogout(pSelf)
            
            bucketname = utilities.getBucketname(username)
            
            # get the available credentials and storage-amount
            credentials = utilities.getCredentials(username)
            results = credentials.fetch(100)
            
            if uploadedFiles:
                # TODO: 'NOTE'
                # check if the necessary attributes (key-name, acl, content-type) were set respectively chosen
                # if not, do nothing and print a hint-message for the user
                # if it is, than do the procedure below...
                
                
                # determine the file-size and maybe some other file-dependent information (blobFile-attribute is a blobInfo-object)
                blobFile = uploadedFiles[0]
                
                if credentials:
                    for result in results:
                        regionname = result.regionname
                        
                        if regionname == utilities.getAmazonText():
                            amazonStorageConnection = utilities.getStorageServiceConnectionByResult(username, result)
                            self.uploadFile(utilities, regionname, amazonStorageConnection, bucketname, blobFile, key, acl)
                            
                        if regionname == utilities.getGoogleText():
                            googleStorageConnection = utilities.getStorageServiceConnectionByResult(username, result)
                            self.uploadFile(utilities, regionname, googleStorageConnection, bucketname, blobFile, key, acl)
                            
                        if regionname == utilities.getOpenStackText():
                            openStackStorageConnection = utilities.getStorageServiceConnectionByResult(username, result)
                            self.uploadFile(utilities, regionname, openStackStorageConnection, bucketname, blobFile, key, acl)
                else:
                    keyList = self.getKeyList(utilities, username, bucketname)
                    print('key-lsit: ', keyList)
                    print('')              
                    
#                    hintText = _('An error occurred - could not get the available credentials')
                    hintText = 'An error occurred - could not get the available credentials'
                    hintColor = 'red'
                    
                    self.callBuilder(userText, username, url, urlText, hintText, hintColor, keyList)
    
                # when the upload is done - redirect to the select-data-view
                pSelf.redirect('/selectdata')
            else:
                keyList = self.getKeyList(utilities, username, bucketname)
    
#                hintText = _('No file chosen - please choose a file')
                hintText = 'No file chosen - please choose a file'
                hintColor = 'red'
                
                self.callBuilder(userText, username, url, urlText, hintText, hintColor, keyList)
        else:
            pSelf.redirect('/')

    # handle the file-upload..
    def uploadFile(self, utilities, regionname, storageConnection, bucketname, blobFile, key, acl, size=None):
        utilities.uploadFileRaidOne(regionname, storageConnection, bucketname, blobFile, key, acl, size)
    
    # loads a list of keys that will be shown in the responsible view (by default: amazon)
    def getKeyList(self, utilities, username, bucketname):
        storageConnection = self.getAmazonStorageConnection(utilities, username)
        
        keyList = utilities.getBucketKeyList(storageConnection, bucketname)
        return keyList
        
    # responsible for the amazon-storage-connection
    def getAmazonStorageConnection(self, utilities, username):
        credentials = utilities.getCredentials(username)
        results = credentials.fetch(100)
        
        if credentials:
            for result in results:
                if result.regionname == utilities.getAmazonText():
                    amazonAccessKey = result.accessKey
                    amazonSecretAccessKey = utilities.decodeSecretAccessKey(username, result.secretAccessKey)
                    amazonEndpointURL = utilities.getAmazonURL()
                    
                    amazonStorageConnection = utilities.getS3Connection(amazonAccessKey, amazonSecretAccessKey, amazonEndpointURL)
                    
                    return amazonStorageConnection
        
    # responsible for the call of the get-method of the BuildStorageInfo-Class
    def callBuilder(self, userText, username, url, urlText, hintText, hintColor, keyList):
        templateValues = {
                          'userText': userText,
                          'user': username,
                          'urlText': urlText,
                          'url': url,
                          'urlText': urlText,
                          'hintText': hintText,
                          'hintColor': hintColor
                          }
        
        builder = BuildStorageInfo()
        builder.get(self, templateValues, keyList)

            
